/* main.c */

#include "app_inc.h"

volatile Filter_Handler_T gFilterHandlerStruct;
volatile Key_Handler_T    gKeyHandlerStruct;
volatile Key_Event_T      gKeyEvent;

static void MyTickerISR(void);

RBUF_Handler_T gRingBufHandlerStruct;
RBUF_Handler_T *gRingBufHandler = &gRingBufHandlerStruct;
uint8_t gRingBufData[20];

int main(void)
{
    Systick_Config_T SystickConfigStruct =
    {
        .CoreClkHz = BSP_CLK_CORECLK_HZ,
        .TicksPerSecond = BSP_TICKERS_PER_SECOND
    };

    /* Initialize the board. */
    BSP_InitSystem();
    BSP_InitStdioUART(115200);
    BSP_InitKeyGPIO();
    
    printf("\r\nKey Example\r\n");
    
    /* Initialize the ring buffer for key events. */
    RBUF_Init(gRingBufHandler, gRingBufData, sizeof(gRingBufData));

    /* Initialize the Filter & Key. */
    GPIO_SetPinDir(BSP_GPIO_KEY1_PORT, BSP_GPIO_KEY1_PIN, false);
    Filter_Init((Filter_Handler_T *)&gFilterHandlerStruct, 0U, 5U); /* 5ms per tick. */
    Key_Init((Key_Handler_T *)&gKeyHandlerStruct,
            200U, /* longDownCountFirst */
            100U  /* longDownCountStep */
    );
    
    Systick_ConfigTicker(&SystickConfigStruct);
    Systick_InstallCallback(MyTickerISR);
    
    while (1)
    {
        /* Get the key event and process it. */
        if (!RBUF_IsEmpty(gRingBufHandler))
        {
            switch (RBUF_GetDataOut(gRingBufHandler))
            {
            case eKey_Event_PressedDownEdge:
                /* Todo: */
                printf("1:eKey_Event_PressedDownEdge\r\n");
                break;
            case eKey_Event_PressedDownLongFirst:
                /* Todo: */
                printf("2:eKey_Event_PressedDownLongFirst\r\n");
                break;
            case eKey_Event_PressedDownLongContinue:
                /* Todo: */
                printf("3:eKey_Event_PressedDownLongContinue\r\n");
                break;
            case eKey_Event_PressedUpEdgeShort:
                /* Todo: */
                printf("4:eKey_Event_PressedUpEdgeShort\r\n");
                break;
            case eKey_Event_PressedUpEdgeLong:
                /* Todo: */
                printf("5:eKey_Event_PressedUpEdgeLong\r\n");
                break;
            default:
                break;
            }
        }
    } /* while */
}

static void MyTickerISR(void)
{
    bool bKeyDownFlag;
    uint8_t u8KeyEvent;

    /* Scan the key and filte the input signal. */
    bKeyDownFlag = !GPIO_GetPinLogic(BSP_GPIO_KEY1_PORT, BSP_GPIO_KEY1_PIN);
    bKeyDownFlag = (bool)Filter_GetFiltedOutput((Filter_Handler_T *)&gFilterHandlerStruct, (uint32_t)bKeyDownFlag);
    
    /* Feed the state machine. */
    Key_GetState((Key_Handler_T *)&gKeyHandlerStruct, bKeyDownFlag);
    
    /* Get the state and fill the event queue. */
    u8KeyEvent = Key_GetEvent((Key_Handler_T *)&gKeyHandlerStruct);
    if (eKey_Event_Nothing != u8KeyEvent)
    {
        RBUF_PutDataIn(gRingBufHandler, u8KeyEvent);
    }
}

/* EOF. */

